<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-班次考勤记录`"
		width="1200px"
		:show-content-loading="showLoading"
		:save-btn-loading="saveBtnLoading"
		append-to-body
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="6">
					<el-form-item class="margin-bottom-10" label="日期" prop="belongDate">
						<jk-date-picker v-model="ruleForm.belongDate" size="medium" class="width-100-percent" placeholder="日期"></jk-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
						<jk-select v-model="ruleForm.workshopId" size="medium" class="width-100-percent" :option-list="workshopList" placeholder="区域"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item class="margin-bottom-10" label="班次" prop="processId">
						<jk-select v-model="ruleForm.scheduleShiftId" size="medium" class="width-100-percent" :option-list="[]" placeholder="班次" @change="onProcessChange"></jk-select>
					</el-form-item>
				</el-col>
				<!--<el-col :span="6">
					<el-form-item class="margin-bottom-10" label="班组" prop="processId">
						<jk-select v-model="ruleForm.scheduleGroupId" size="medium" class="width-100-percent" :option-list="[]" placeholder="班组" @change="onProcessChange"></jk-select>
					</el-form-item>
				</el-col>-->
				<el-col :span="6">
					<el-form-item class="margin-bottom-10" label="统计员" prop="processId">
						<jk-select v-model="ruleForm.scheduleGroupId" size="medium" class="width-100-percent" :option-list="[]" placeholder="统计员" @change="onProcessChange"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="备注">
						<el-input v-model="ruleForm.remark" type="textarea" :rows="1" placeholder="" />
					</el-form-item>
				</el-col>
			</el-row>
			<div>
				<!--<div ref="box2" class="flex-between-center margin-bottom-4">
					<el-button :disabled="!ruleForm.processId" type="primary" icon="el-icon-circle-plus" size="mini" @click="onAddBtn">翻改机台</el-button>
					<div class="flex-end-center">
						<el-button
							type="warning"
							icon="el-icon-upload2"
							size="mini"
							@click="onExportExcel"
						>导出</el-button>
					</div>
				</div>-->
				<el-row :gutter="10">
					<el-col :span="5">
						<div class="box-title">未打卡</div>
						<jk-table ref="jkTable" :span-method="mergeColMethod" border :data="tableData1" :height="dialogTableHeight - 50">
							<vxe-column title="岗位" align="left" field="postName" :width="80" />
							<vxe-table-column field="empList" title="人员" align="left" :min-width="80">
								<template slot-scope="scope">
									<div class="flex-start-center">
										<el-tag>张三</el-tag>
									</div>
								</template>
							</vxe-table-column>
							<vxe-column title="操作" width="60" align="center">
								<template slot-scope="scope">
									<el-button size="mini" icon="el-icon-delete" type="text" @click="ruleForm.machineChangeList.splice(scope.rowIndex, 1)"></el-button>
								</template>
							</vxe-column>
						</jk-table>
					</el-col>
					<el-col :span="11">
						<div class="box-title">迟到早退</div>
						<jk-table ref="jkTable" :span-method="mergeColMethod" border :data="tableData1" :height="dialogTableHeight - 50">
							<vxe-column title="岗位" align="left" field="postName" :width="80" />
							<vxe-table-column field="empList" title="人员" align="left" :min-width="80">
								<template slot-scope="scope">
									<div class="flex-start-center">
										<el-tag>张三</el-tag>
									</div>
								</template>
							</vxe-table-column>
							<vxe-column title="上班打卡时间" align="left" field="machineCode" :width="100" />
							<vxe-column title="下班打卡时间" align="left" field="machineCode" :width="100" />
							<vxe-column title="迟到原因" align="left" field="machineCode" :width="150">
								<template slot-scope="scope">
									<div class="flex-start-center">
										<jk-select v-model="scope.row.aaa"></jk-select>
									</div>
								</template>
							</vxe-column>
							<vxe-column title="早退原因" align="left" field="machineCode" :width="150">
								<template slot-scope="scope">
									<div class="flex-start-center">
										<jk-select v-model="scope.row.aaa"></jk-select>
									</div>
								</template>
							</vxe-column>
							<vxe-column title="操作" width="60" align="center">
								<template slot-scope="scope">
									<el-button size="mini" icon="el-icon-delete" type="text" @click="ruleForm.machineChangeList.splice(scope.rowIndex, 1)"></el-button>
								</template>
							</vxe-column>
						</jk-table>
					</el-col>
					<el-col :span="8">
						<div class="box-title">请假</div>
						<jk-table ref="jkTable" :span-method="mergeColMethod" border :data="tableData1" :height="dialogTableHeight - 50">
							<vxe-column title="岗位" align="left" field="postName" :width="80" />
							<vxe-table-column field="empList" title="人员" align="left" :min-width="80">
								<template slot-scope="scope">
									<div class="flex-start-center">
										<el-tag>张三</el-tag>
									</div>
								</template>
							</vxe-table-column>
							<vxe-column title="请假原因" align="left" field="machineCode" :width="150">
								<template slot-scope="scope">
									<div class="flex-start-center">
										<jk-select v-model="scope.row.aaa"></jk-select>
									</div>
								</template>
							</vxe-column>
							<vxe-column title="操作" width="60" align="center">
								<template slot-scope="scope">
									<el-button size="mini" icon="el-icon-delete" type="text" @click="ruleForm.machineChangeList.splice(scope.rowIndex, 1)"></el-button>
								</template>
							</vxe-column>
						</jk-table>
					</el-col>

					<!--<el-col :span="12">
						<div class="box-title">异常人员</div>
						<jk-table ref="jkTable" :span-method="mergeColMethod" border :data="tableData1" :height="dialogTableHeight - 40">
							<vxe-column title="类型" align="left" field="typeName" :width="80" />
							<vxe-column title="岗位" align="left" field="postName" :width="80" />
							<vxe-table-column field="empList" title="人员" align="left" :min-width="80">
								<template slot-scope="scope">
									<div class="flex-start-center">
										<el-tag class="item-gap">张三</el-tag>
										<el-tag>李四</el-tag>
									</div>
								</template>
							</vxe-table-column>
							<vxe-column title="操作" width="60" align="center">
								<template slot-scope="scope">
									<el-button size="mini" icon="el-icon-delete" type="text" @click="ruleForm.machineChangeList.splice(scope.rowIndex, 1)"></el-button>
								</template>
							</vxe-column>
						</jk-table>
					</el-col>-->
					<!--<el-col :span="12">
						<div class="box-title">常白班</div>
						<jk-table ref="jkTable" :span-method="mergeColMethod" border :data="tableData1" :height="dialogTableHeight - 40">
							<vxe-column title="类型" align="left" field="typeName" :width="80" />
							<vxe-column title="岗位" align="left" field="postName" :width="80" />
							<vxe-table-column field="empList" title="人员" align="left" :min-width="80">
								<template slot-scope="scope">
									<div class="flex-start-center">
										<el-tag class="item-gap">张三</el-tag>
										<el-tag>李四</el-tag>
									</div>
								</template>
							</vxe-table-column>
							<vxe-column title="操作" width="60" align="center">
								<template slot-scope="scope">
									<el-button size="mini" icon="el-icon-delete" type="text" @click="ruleForm.machineChangeList.splice(scope.rowIndex, 1)"></el-button>
								</template>
							</vxe-column>
						</jk-table>
					</el-col>-->
				</el-row>
			</div>
		</el-form>
		<checkbox-machine-dialog
			:form-data="ruleForm"
			:default-select-rows="ruleForm.machineChangeList"
			check-key-name="id"
			:dialog-state="checkboxMachineDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxMachineDialog"
			@on-confirm="onConfirmBtnOfCheckboxMachineDialog"
		></checkbox-machine-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        productionMachineChangeRecordCreate,
        productionMachineChangeRecordUpdate,
        productionMachineChangeRecordGet
    } from '../../../api/production/xsDailyRenovateStatistic';
    import Sortable from 'sortablejs';
    import { formatDate } from '../../../utils/jk/jk-tool';
    import checkboxMachineDialog from './components/checkbox-machine-dialog';
    export default {
        components: {
            checkboxMachineDialog
        },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                tableData1: [
                    {
                        typeName: '未打卡',
                        postName: '细纱挡车工',
                        empList: [{}, {}, {}]
                    },
                    {
                        typeName: '未打卡',
                        postName: '梳棉挡车工',
                        empList: [{}, {}, {}]
                    },
                    {
                        typeName: '迟到早退',
                        postName: '细纱挡车工',
                        empList: [{}, {}, {}]
                    },
                    {
                        typeName: '迟到早退',
                        postName: '梳棉挡车工',
                        empList: [{}, {}, {}]
                    },
                    {
                        typeName: '请假',
                        postName: '细纱挡车工',
                        empList: [{}, {}, {}]
                    },
                    {
                        typeName: '请假',
                        postName: '梳棉挡车工',
                        empList: [{}, {}, {}]
                    }
                ],
                workshopList: [],
                processList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    belongDate: '',
                    workshopId: null,
                    processId: null,
                    ifBase: 1,
                    machineChangeList: []
                },
                rules: {
                    belongDate: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }]
                },
                checkboxMachineDialogState: false
            };
        },
        methods: {
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['typeName']; // 根据字段判断数据相同的合并
                const cellValue = row[column.property];
                if (cellValue && fields.includes(column.property)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.property] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.property] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onExportExcel() {
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = ['机台', '生产类型', '客户', '品种', '批号', '改前品种', '改前批号'];
                    const filterVal = ['machineCode', 'ifTestName', 'customerName', 'productName', 'batchCode', 'preProductName', 'preBatchCode'];
                    const list = this.$refs.jkTable.$refs.xTable.getTableData().tableData.map(x => {
                        x.ifTestName = x.ifTest ? '试产打样' : '正式生产';
                        return x;
                    });
                    const multiHeader = [
                        [`改批计划表  日期${this.ruleForm.belongDate}`, '', '', '', '', '', ''] // 第一行
                    ]; // 前两行的表头数据，二维数组，不够的用空白补全
                    const data = list.map(v => filterVal.map(j => v[j]));
                    const merges = ['A1:G1']; // 合并单元格的数据，
                    excel.export_json_to_excel({
                        multiHeader,
                        header: tHeader,
                        merges,
                        data,
                        filename: `翻改统计(${this.ruleForm.belongDate}/${this.ruleForm.workshopName}/${this.ruleForm.processName})`,
                        autoWidth: true,
                        // merges: merges,
                        bookType: 'xlsx'
                    });
                });
            },
            onProcessChange(e) {
                const processItem = this.processList.find(x => x.id === e) || {};
                this.$set(this.ruleForm, 'processCode', processItem.code);
                this.$set(this.ruleForm, 'processName', processItem.name);
            },
            onAddBtn() {
                this.checkboxMachineDialogState = true;
            },
            onConfirmBtnOfCheckboxMachineDialog(arr) {
                arr.forEach(x => {
                    this.ruleForm.machineChangeList.push(x);
                });
                this.sorRowData();
                this.checkboxMachineDialogState = false;
            },
            sorRowData() {
                this.$refs.jkTable.$refs.xTable.sort({ field: 'machineCode' }, 'desc');
            },
            onVisibleChangeOfCheckboxMachineDialog(e) {
                this.checkboxMachineDialogState = e;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;
                const processItem = this.processList.find(x => x.id === params.processId) || {};
                params.processCode = processItem.code;
                params.processName = processItem.name;
                params.machineChangeList.forEach((x, idx) => {
                    x.sortNum = idx + 1;
                });
                // 新增
                if (!this.dataId) {
                    this.ruleForm.id = null;
                    productionMachineChangeRecordCreate(params).then(res => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            this.$emit('on-finish');
                        }
                    });
                    return;
                }

                // 编辑
                productionMachineChangeRecordUpdate(params).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onConfirmBtn(type) {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionMachineChangeRecordGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                        this.sorRowData();
                    }
                });
            },
            loadSortTable() {
                this.$nextTick(() => {
                    const xTable = this.$refs.jkTable;
                    this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
                        handle: '.drag-btn',
                        animation: 500,
                        onEnd: ({ newIndex, oldIndex }) => {
                            const currRow = this.ruleForm.machineChangeList.splice(oldIndex, 1)[0];
                            this.ruleForm.machineChangeList.splice(newIndex, 0, currRow);
                        }
                    });
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.processList = this.$store.state.user.userProcess.processList;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.$set(this.ruleForm, 'workshopCode', this.$store.state.user.userWorkshop.defaultWorkshopCode);
                    this.$set(this.ruleForm, 'workshopName', this.$store.state.user.userWorkshop.defaultWorkshopName);
                    this.$set(this.ruleForm, 'processId', this.$store.state.user.userProcess.defaultProcessId);
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        mounted() {
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.loadSortTable();
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
    .box-title {
        height: 38px;
        font-size: 15px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #e8eaec;
        border: solid 1px #dcdee2;
        border-bottom: none;
        margin-bottom: -1px;
        border-radius: 4px 4px 0 0;
    }
</style>
